<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="楼栋" prop="buildingId">
        <el-select v-model="formData.buildingId" placeholder="请选择楼栋" :disabled="formLoading">
          <el-option v-for="building in buildingsList" :key="building.id" :label="building.buildingName" :value="building.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="门牌号" prop="roomNo">
        <el-input v-model="formData.roomNo" placeholder="请输入门牌号" />
      </el-form-item>
      <el-form-item label="宿舍类型" prop="roomType">
        <el-select v-model="formData.roomType" placeholder="请选择宿舍类型" style="width: 100%">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.DORM_ROOM_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="房价" prop="price">
        <el-input v-model="formData.price" placeholder="请输入房价" />
      </el-form-item>
      <el-form-item label="入住人数" prop="currentOccupancy">
        <el-input v-model="formData.currentOccupancy" placeholder="请输入入住人数" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status" style="width: 100%; display: flex; gap: 20px;">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.DORM_ROOM_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { itoriesApi, itories } from '@/api/dorm/dormitories'
import { BuildingsApi } from '@/api/dorm/buildings'

/** 宿舍 表单 */
defineOptions({ name: 'itoriesForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const buildingsList = ref<any[]>([]) // 楼栋列表

const formData = ref({
  id: undefined,
  buildingId: undefined, // 直接使用楼栋ID
  roomNo: undefined,
  roomType: undefined,
  price: undefined,
  currentOccupancy: undefined,
  status: undefined,
})
const formRules = reactive({
  buildingId: [{ required: true, message: '楼栋不能为空', trigger: 'blur' }],
  roomNo: [{ required: true, message: '门牌号不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '房价不能为空', trigger: 'blur' }],
  currentOccupancy: [{ required: true, message: '入住人数不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 获取所有楼栋列表 */
/** 获取所有楼栋列表 */
const getBuildingsList = async () => {
  try {
    const data = await BuildingsApi.getBuildingsAll() // 使用新的getBuildingsAll方法获取所有楼栋
    // 只保留楼栋id和buildingName字段，确保下拉框能正常显示
    buildingsList.value = data.map(building => ({ id: building.id, buildingName: building.buildingName }))
  } catch (error) {
    message.error('获取楼栋列表失败')
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  
  // 加载楼栋列表
  await getBuildingsList()
  
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const dormData = await itoriesApi.getitories(id)
      // 直接使用dormData中的buildingId，不再需要转换
      formData.value = dormData
    } finally {
      formLoading.value = false
    }
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    // 直接使用formData.value，因为buildingId已经是表单字段
    const data = formData.value as unknown as itories
    if (formType.value === 'create') {
      await itoriesApi.createitories(data)
      message.success(t('common.createSuccess'))
    } else {
      await itoriesApi.updateitories(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    buildingId: undefined,
    roomNo: undefined,
    roomType: undefined,
    price: undefined,
    currentOccupancy: undefined,
    status: undefined,
  }
  formRef.value?.resetFields()
}

// 提供 open 方法，用于打开弹窗
defineExpose({ open })
</script>